﻿using Learun.Application.Base.SystemModule;
using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-03-03 17:00
    /// 描 述：元件库文件表
    /// </summary>
    public class ec_library_fileService
    {
        #region 仓储
        Repository<ec_projectEntity> _projectRepository => new Repository<ec_projectEntity>();
        Repository<ec_library_fileEntity> _libraryFileRepository => new Repository<ec_library_fileEntity>();
        Repository<AnnexesFileEntity> _annexesFileRepository => new Repository<AnnexesFileEntity>();
        #endregion
        #region 获取数据
        /// <summary>
        /// 查询某个ID在系统图里用到的块
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns></returns>
        public List<TreeModel> GetFileOnSystemDwgByTagId(string ProjectId, string DataItemNames)
        {
            try
            {
                //参考写法
                if (string.IsNullOrEmpty(ProjectId))
                {
                    return null;
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    if (ProjectEntity == null)
                    {
                        return null;
                    }
                    var ProjIndex = ProjectEntity.ProjectIndex;
                    string SQL = "";
                    var pixelBLL = new ec_enginedata_pixelBLL();
                    var drawingBLL = new ec_drawing_fileBLL();
                    var drawingTypeBLL = new ec_drawing_catalogueBLL();
                    var libraryFileBLL = new ec_library_fileBLL();
                    var FrameListFlg = new ec_projectSettingsBLL().GetEntity("所属系统", ProjectId);
                    if (FrameListFlg != null)
                    {
                        //从setting找属性
                        var property = new ec_propertyBLL().GetList("{PropertyName:\"" + FrameListFlg.SettingValue + "\",ProjectId:\"" + ProjectId + "\"}").FirstOrDefault();
                        if (property != null)
                        {
                            //var EngineDataBLL = new ec_enginedataBLL();
                            SQL = $@"SELECT DISTINCT t.EngineDataID,t.tagnumber,T3.DefaultLayoutLibFileID,T9.FileMD5 DefaultMD5,t8.LibraryFileName,t8.LibraryFileID,t8.FileMD5,t3.ObjectTypeName,t3.ObjectTypeNameEN,t2.PropertyValue,t5.DrawingType,t6.DataItemName
FROM ec_enginedata_{ProjIndex} t
left join ec_enginedata_property_{ProjIndex} t2 on t.EngineDataID=t2.EngineDataID
join ec_objecttype_{ProjIndex} t3 on t3.ObjectTypeID=t.ObjectTypeID 
join ec_enginedata_pixel_{ProjIndex} t4 on t4.EngineDataID=t.EngineDataID
join ec_drawing_file_{ProjIndex} t5 on t5.DrawingFileID=t4.DrawingFileID
join ec_dataitemdetail_{ProjIndex} t6 on t6.DataItemDetailID=t5.DrawingType
join ec_dataitem_{ProjIndex} t7 on t7.DataItemID=t6.DataItemID
LEFT join ec_library_file_{ProjIndex} t8 on t8.LibraryFileID=t4.LibraryFileID
LEFT join ec_library_file_{ProjIndex} t9 on t9.LibraryFileID=T3.DefaultLayoutLibFileID
where t2.PropertyName = '{property.PropertyName}' and t7.DataItemCode='Be_DrawingType' and t6.DataItemName='系统图' and t2.PropertyValue IN ('{string.Join("','", DataItemNames.Split(','))}')
ORDER BY T.EngineDataID";
                        }
                    }


                    //var DT = this.BaseRepository().FindTable(SQL);
                    var DT = SqlSugarHelper.Db.Ado.GetDataTable(SQL);
                    List<TreeModel> treeList = new List<TreeModel>();
                    foreach (DataRow item in DT.Rows)
                    {

                        TreeModel node = new TreeModel();
                        //1.先用某个位号在系统图上的某一个图元
                        //2.再用对象类型的默认图元
                        //3.客户端用自己的
                        var library = libraryFileBLL.GetEntity(item["LibraryFileID"].ToString() == "" ? item["DefaultLayoutLibFileID"].ToString() : item["LibraryFileID"].ToString(), ProjectId); 
                       
                        node.id = item["EngineDataID"].ToString();
                        node.text = item["tagnumber"].ToString();
                        node.value = item["ObjectTypeName"].ToString();
                        node.showcheck = false;
                        node.checkstate = 0;
                        node.isexpand = true;
                        node.parentId = "";
                        node.NodeExtData = library ;
                        if (!treeList.Any(X => X.id == node.id))
                        {

                            treeList.Add(node);

                        }
                        else
                        {
                            //如果有了
                            var EXIST = treeList.FirstOrDefault(X => X.id == node.id && X.text == "");
                            if (EXIST != null)
                            {
                                EXIST.text = node.text;
                                EXIST.value = node.value;
                            }

                        }



                    }
                    return treeList;
                }


            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 获取实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public ec_library_fileEntity GetEntity(string keyValue, string ProjectId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    return _libraryFileRepository.GetById(keyValue);
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    var strSql = new StringBuilder();
                    strSql.Append($@"SELECT * FROM ec_library_file_{ProjectEntity.ProjectIndex} WHERE LibraryFileID = @LibraryFileID ");
                    //List<ec_library_fileEntity> list = this.BaseRepository().FindList<ec_library_fileEntity>(strSql.ToString(), new { LibraryFileID = keyValue }).ToList();
                    //return list.FirstOrDefault();
                    return SqlSugarHelper.Db.Ado.SqlQuerySingle<ec_library_fileEntity>(strSql.ToString(), new { LibraryFileID = keyValue });
                }

            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string keyValue, string ProjectId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    _libraryFileRepository.Delete(t => t.LibraryFileID == keyValue);
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    SqlSugarHelper.Db.Ado.ExecuteCommand($" DELETE FROM ec_library_file_{ProjectEntity.ProjectIndex} WHERE LibraryFileID = @LibraryFileID  ", new { LibraryFileID = keyValue });
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string keyValue, ec_library_fileEntity entity, string ProjectId)
        {
            try
            {
                if (!string.IsNullOrEmpty(keyValue))
                {
                    entity.Modify(keyValue);
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        _libraryFileRepository.Update(entity);
                    }
                    else
                    {
                        var ProjectEntity = _projectRepository.GetById(ProjectId);
                        //this.BaseRepository().UpdateByNoMap(entity, $"ec_library_file_{ProjectEntity.ProjectIndex}", "LibraryFileID");
                        _libraryFileRepository.AsUpdateable(entity).AS($"ec_library_file_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }
                }
                else
                {
                    entity.Create();
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        _libraryFileRepository.Insert(entity);
                    }
                    else
                    {
                        var ProjectEntity = _projectRepository.GetById(ProjectId);
                        //this.BaseRepository().InsertByNoMap(entity, $"ec_library_file_{ProjectEntity.ProjectIndex}");
                        _libraryFileRepository.AsInsertable(entity).AS($"ec_library_file_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }


        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void MuliteImport(List<ec_library_fileEntity> addFileEntities, List<ec_library_fileEntity> updateFileEntities, List<AnnexesFileEntity> annexesFileEntities, string ProjectId)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    _libraryFileRepository.InsertRange(addFileEntities);
                    _libraryFileRepository.UpdateRange(updateFileEntities);
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    //db.InsertByNoMap(addFileEntities, $"ec_library_file_{ProjectEntity.ProjectIndex}");
                    //db.UpdateByNoMap(updateFileEntities, $"ec_library_file_{ProjectEntity.ProjectIndex}", "LibraryFileID");
                    _libraryFileRepository.AsInsertable(addFileEntities).AS($"ec_library_file_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    _libraryFileRepository.AsUpdateable(updateFileEntities).AS($"ec_library_file_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                }
                _annexesFileRepository.InsertRange(annexesFileEntities);
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 修改集合数据,新增附件数据集合
        /// <summary>
        /// <returns></returns>
        public void SaveDataAndAnnexes(List<ec_library_fileEntity> entityList, List<AnnexesFileEntity> listAnnexesFile, string ProjectId)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                if (!string.IsNullOrEmpty(ProjectId))
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    //db.UpdateByNoMap(entityList, $"ec_library_file_{ProjectEntity.ProjectIndex}", "LibraryFileID");
                    _libraryFileRepository.AsUpdateable(entityList).AS($"ec_library_file_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    _annexesFileRepository.InsertRange(listAnnexesFile);
                }
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion

    }
}
